package com.jrh.web.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jrh.dal.CategoryDao;
import com.jrh.domain.entity.Atlas;
import com.jrh.domain.entity.Category;
import com.jrh.web.admin.form.AdminCategoryForm;
import com.jrh.web.admin.form.AdminFormCopier;
import com.jrh.web.admin.form.AdminAtlasForm;

/**
 * 类目后台
 * 
 * @author jasen.hsu.cn@gmail.com 2012-7-16 下午2:11:52
 */
@Controller
@RequestMapping("/admin/category")
public class AdminCategoryController {

    @Autowired
    private CategoryDao categoryDao;

    @RequestMapping("")
    public String listParent(Model model) {
        List<Category> parentCategorys = categoryDao.listParentCategory();
        model.addAttribute("_data_", parentCategorys);
        model.addAttribute("parents", parentCategorys);
        return "admin/category/list";
    }

    @RequestMapping("/{id}")
    public String listChild(@PathVariable Long id, Model model) {
        List<Category> childCategorys = categoryDao.listChildCategory(id);
        List<Category> parentCategorys = categoryDao.listParentCategory();
        model.addAttribute("parents", parentCategorys);
        model.addAttribute("_data_", childCategorys);
        return "admin/category/list";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/update/{id}")
    public String update(@PathVariable Long id, Model model) {
        Category category = categoryDao.load(id);
        List<Category> parentCategorys = categoryDao.listParentCategory();
        model.addAttribute("parents", parentCategorys);
        model.addAttribute("_data_", category);
        return "admin/category/edit";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/update")
    public String doUpdate(@ModelAttribute("categoryForm") AdminCategoryForm categoryForm) {
        Category category = AdminFormCopier.convert(categoryForm, null);
        categoryDao.update(category);
        return "admin/success";
        //return "redirect:/admin/category.htm";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public String doCreate(@ModelAttribute("categoryForm") AdminCategoryForm categoryForm) {
        Category category = AdminFormCopier.convert(categoryForm, null);
        categoryDao.create(category);
        return "redirect:/admin/category.htm";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/delete/{id}")
    public String delete(@PathVariable Long id) {
        categoryDao.delete(id);
        return "redirect:/admin/category.htm";
    }

}
